/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.renderer;

import com.jb.web.bean.UIComponentImpl;
import com.jb.web.context.WebContext;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jb.faces.component.UIComponent;
import com.jb.web.bean.Text;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Date;


public class DefaultRenderer extends RendererImpl {
    protected String getValue(WebContext ctx, Text itemToRender) {
        if(!itemToRender.isExpression())
            return  itemToRender.getValue();
        
        Object value = evaluateObject(ctx, itemToRender, itemToRender.getValue());

        if (((value == null) || (value.toString().length() == 0)) && (itemToRender.getDefaultValue() != null)) {
            value = evaluateObject(ctx, itemToRender, itemToRender.getDefaultValue());
        }

        if (value instanceof Calendar) {
            value = ((Calendar) value).getTime();
        }

        if (value instanceof String) {
            value = crtobr((String) value);
        }

        if (value instanceof Date) {
            String formatStr = itemToRender.getValueFormat();

            if (formatStr != null) {
                try {
                    SimpleDateFormat simpleDate = 
                        (SimpleDateFormat)SimpleDateFormat.getDateInstance();
                    simpleDate.applyPattern(formatStr);
                    value = simpleDate.format((Date)value);
                } catch (Exception e) {
                    value ="";
                    ctx.addErrorMessage(itemToRender, "Failed to convert date field "+e);
                }
            } else {
                value = SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL).format((Date) value);
            }
        }

        if (value instanceof Number) {
            String formatStr = itemToRender.getValueFormat();

            if (formatStr != null) {
                NumberFormat nf = NumberFormat.getNumberInstance();

                value = nf.format(value);
            }
        }

        // itemToRender.setEvaluatedValue(value);
        if (isEmptyString(value) && !ctx.isRunTime() && itemToRender.isDesignable()) {
            value = itemToRender.getValue();

            if (isEmptyString(value)) {
                value = "&nbsp;";
            }
        }

        if (value == null) {
            return "";
        }

        String strValue = value.toString();

        if (!isEmptyString(itemToRender.getWidth())) {
            try {
                int length = Integer.valueOf(itemToRender.getWidth()).intValue();

                if (length < strValue.length()) {
                    return strValue.substring(0, length) + "...";
                }
            } catch (Exception e) {
                return strValue;
            }
        }
        return strValue;
    }
    
    public static String brtocr(String value) {
        if (value == null) {
            return value;
        }

        Pattern CRLF = Pattern.compile("(<BR>)");
        Matcher m = CRLF.matcher(value);

        if (m.find()) {
            value = m.replaceAll("\n");
        }

        return value;
    }

    public static void checkScript(String value) {
        String lowerCase = value.toLowerCase();

        if ((lowerCase.indexOf("<script") != -1) || (lowerCase.indexOf("<object") != -1)) {
            throw new SecurityException("java script, or object are not allowed");
        }
    }

    public static String crtobr(String value) {
        if (value == null) {
            return value;
        }

        Pattern CRLF = Pattern.compile("(\r\n|\r|\n|\n\r)");
        Matcher m = CRLF.matcher(value);

        if (m.find()) {
            value = m.replaceAll("<BR>");
        }

        return value;
    }

    public StringBuffer renderBegin(WebContext pCtx, UIComponent itemToRender) {
        UIComponentImpl hItem = (UIComponentImpl) itemToRender;
        StringBuffer html = new StringBuffer("<DIV ").append(getEditScript(pCtx, hItem))
                                                     .append(addTagProperty("width", "100%", null)).append(">");

        String value = hItem.getId();
        html.append(value);

        return html.append("</DIV>");
    }

    public StringBuffer renderChildren(WebContext pCtx, UIComponent itemToRender) {
        return new StringBuffer();
    }

    public StringBuffer renderEnd(WebContext pCtx, UIComponent itemToRender) {
        return new StringBuffer();
    }

    protected String escape(String value) {
        return value;
    }
}
